#include "shader.h"
#include <string>

using namespace std;

/**
	Creates a new Shader object.
*/
Shader::Shader(string fragmentFileName, string vertexFileName)
{

	this->v = glCreateShader(GL_VERTEX_SHADER);
	this->f = glCreateShader(GL_FRAGMENT_SHADER);

	const GLchar* sourcev = textFileRead(&vertexFileName[0]);
	const GLchar* sourcef = textFileRead(&fragmentFileName[0]);
	glShaderSource(this->v, 1, &sourcev, NULL);
	glShaderSource(this->f, 1, &sourcef, NULL);

	glCompileShader(this->v);
	glCompileShader(this->f);

	this->p = glCreateProgram();

	glAttachShader(this->p, this->v);
	glAttachShader(this->p, this->f);

	glLinkProgram(this->p);

	int infologLength = 0;
	int charsWritten  = 0;
	char *infoLog;
	glGetProgramiv(p, GL_INFO_LOG_LENGTH,&infologLength);
	if (infologLength > 0)
	{
		infoLog = (char *)malloc(infologLength);
		glGetProgramInfoLog(p, infologLength, &charsWritten, infoLog);
		//printf("%s\n",infoLog);
		free(infoLog);
	}
}

/**
	Destroys the current Shader object.
*/
Shader::~Shader()
{
	// nothin to do
}

void Shader::turnShadersOn()
{
	//printf("turning ON program\n");
	glUseProgram(this->p);
}


void Shader::turnShadersOff()
{
	//printf("turning OFF program\n");
	glUseProgram(NULL);
}

/**
	Reads the file and returns a NULL-terminated string
	of the file contents.
*/
char *Shader::textFileRead(const char *fn)
{
	FILE *fp;
	char *content = NULL;

	int count=0;

	if (fn != NULL) {
		fp = fopen(fn,"rt");

		if (fp != NULL) {

			fseek(fp, 0, SEEK_END);
			count = ftell(fp);
			rewind(fp);

			if (count > 0) {
				content = (char *)malloc(sizeof(char) * (count+1));
				count = fread(content,sizeof(char),count,fp);
				content[count] = '\0';
			}
			fclose(fp);
		}
	}
	return content;
}


/**
	Writes the specified string "s", to the specified file "fn".
*/
int Shader::textFileWrite(char *fn, char *s) 
{

	FILE *fp;
	int status = 0;

	if (fn != NULL) {
		fp = fopen(fn,"w");

		if (fp != NULL) {

			if (fwrite(s,sizeof(char),strlen(s),fp) == strlen(s))
				status = 1;
			fclose(fp);
		}
	}
	return(status);
}
